import Vue from 'vue'
import Vuex from 'vuex'
import { login } from '@/api/users'
import { setStorage, getStorage, removeStorage } from '@/utils/storage'

Vue.use(Vuex)

const key = 'vue-shop-user-info'
const time = 'time-stamp-key'

export default new Vuex.Store({
  state: {
    userInfo: getStorage(key) || {},
    rights: []
  },
  mutations: {
    login (state, userInfo) {
      state.userInfo = userInfo
      setStorage(key, userInfo)
    },
    logOut (state) {
      state.userInfo = {}
      removeStorage(key)
    }
  },
  actions: {
    async login ({ commit }, loginData) {
      const userInfo = await login(loginData)
      commit('login', userInfo)
      setStorage(time, Date.now())
    }
  }
})
